<?php
namespace app\interfaces\controller;

use app\interfaces\model\MemberShoppingCart as MemberShoppingCartModel;
use app\interfaces\model\Sale;
use app\interfaces\model\ShopGoods as ShopGoodsModel;
use app\interfaces\model\ShopSpecAttr as ShopSpecAttrModel;
use app\interfaces\model\Limited as LimitedModel;
use think\Db;
use think\Cache;
use think\Request;
use think\Exception;

class MemberShoppingCart
{

    /*
     * 用户端 - 添加购物车
     * @param  string $id 商品 / 店铺ID
     * @param  string $user_id  会员ID
     * @param  string $attr     商品规格
     * @param  string $price    商品价格
     * @param  string $number   商品数量
     */
    public function cart_create()
    {

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['id']) || empty($data['user_id']) || empty($data['price']) || empty($data['number'])) throw new Exception('not Empty');

        // 是否是本店铺
        $member = ShopGoodsModel::where(['id' => $data['id']])->field('member_id,price,inventory')->find();

        if ($member['member_id'] == $data['user_id']) return ['code' => 401, 'message' => '不能添加自己的商品'];

        // 判断数量是否够
        if (!empty($data['attr'])) {

            $number = ShopSpecAttrModel::where(['attribute' => $data['attr'], 'goods_id' => $data['id']])->value('inventory');

            if ($number < $data['number']) return ['code' => 401, 'message' => '商品数量不足'];

        } else {

            if ($member['inventory'] < $data['number']) return ['code' => 401, 'message' => '商品数量不足'];

        }

        $model = new MemberShoppingCartModel();

        // 判断是否存在
        $find = $model->where(['member_id' => $data['user_id'], 'goods_id' => $data['id'], 'attr' => $data['attr']])->value('number');

        if (!empty($find)) {

            // $result = $model->where(['member_id' => $data['user_id'], 'goods_id' => $data['id'], 'attr' => $data['attr']])->setInc('number', $data['number']);
            $result = $model->where(['member_id' => $data['user_id'], 'goods_id' => $data['id'], 'attr' => $data['attr']])
                ->update(['number' => ($find + $data['number']), 'price' => $data['price']]);

        } else {

            if (!empty($data['attr']) && !empty($data['limited_status'])) {
                $price = Sale::where(['goods_id' => $data['id']])->value('price');
            } else if (!empty($data['attr']) && empty($data['limited_status'])) {
                $price = ShopSpecAttrModel::where(['attribute' => $data['attr'], 'goods_id' => $data['id']])->value('price');
            } else {
                $price = $member['price'];
            }

            $information = [
                'member_id' => $data['user_id'],
                'goods_id' => $data['id'],
                'price' => $price,
                'number' => $data['number'],
                'attr' => $data['attr'],

            ];

            $result = $model->save($information);

        }

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];
    }

    /*
     * 用户端 - 猜你喜欢
     * @param  string $user_id 唯一标示
     */
    public function cart_related()
    {

        $condition['state'] = ['eq', 1];
        if (Cache::get('web_commodity_audit') == 'Y') $condition['status'] = ['eq', '1'];
        if (Cache::get('web_related') == 'Y') $condition['related'] = ['eq', '1'];

        // 猜你喜欢
        $like_list = ShopGoodsModel::where($condition)
            ->field('id,title,price,thumb_img,rebate_percentage,recommend,related,sale_number')
            ->limit(10)
            ->order(['rand()' => 'desc'])
            ->select();

        return ['code' => 200, 'message' => '成功', 'data' => $like_list];

    }

    /*
     * 用户端 - 购物车列表
     * @param  string $user_id 唯一标示
     */
    public function cart_list()
    {

        // 获取参数
        $user_id = Request::instance()->param('user_id');

        if (empty($user_id)) throw new Exception('not Empty');

        // 查询商品ID
        $result = Db::view('member_shopping_cart', 'id as cart_id,goods_id,attr,number,price,member_id')
            ->view('shop_goods', 'id,title,thumb_img,rebate_percentage', 'shop_goods.id = member_shopping_cart.goods_id')
            //->view('shop', 'member_id,title as shop_title', 'shop_goods.member_id = shop.member_id','left')
            ->where(['member_shopping_cart.member_id' => $user_id])
            ->order('id','desc')
            ->select()->toArray();

        return ['code' => 200, 'message' => '成功', 'data' => $result];

    }

    /*
     * 用户端 - 购物车查看商品规格
     * @param  string $id 唯一标示
     */
    public function cart_attr()
    {

        // 获取参数
        $id = Request::instance()->param('id');

        if (empty($id)) throw new Exception('not Empty');

        // 查询商品规格
        $model = new ShopGoodsModel();
        $result = $model->where(['id' => $id])->field('goods_attr')->find();

        return ['code' => 200, 'message' => '成功', 'data' => $result];

    }

    /*
     * 用户端 - 更新购物车
     * @param  string $id       商品ID
     * @param  string $cart_id  购物车ID
     * @param  string $user_id  会员ID
     * @param  string $attr     商品规格
     * @param  string $number   商品数量
     */
    public function cart_update()
    {

        // 获取参数
        $id = Request::instance()->param('id');
        $cart_id = Request::instance()->param('cart_id');
        $user_id = Request::instance()->param('user_id');
        $attr = Request::instance()->param('attr');
        $number = Request::instance()->param('number');

        if (empty($cart_id) || empty($id) || empty($attr) || empty($user_id) || empty($number)) throw new Exception('not Empty');

        // 价格
        $price = ShopSpecAttrModel::where(['goods_id' => $id, 'attribute' => $attr])->value('price');

        $find = MemberShoppingCartModel::where(['goods_id' => $id, 'attr' => $attr, 'member_id' => $user_id])->value('id');

        // 判断数量是否够
        if (!empty($attr)) {

            $update_number = ShopSpecAttrModel::where(['attribute' => $attr, 'goods_id' => $id])->value('inventory');
            if ($update_number < $number) return ['code' => 401, 'message' => '商品数量不足'];

        } else {
            $update_number = ShopGoodsModel::where(['id' => $id])->value('inventory');
            if ($update_number < $number) return ['code' => 401, 'message' => '商品数量不足'];

        }

        // 更新
        if (!empty($find)) {

            // 读取数量
            $shopping_number = MemberShoppingCartModel::where(['id' => $cart_id])->value('number');

            if (empty($shopping_number)) throw new Exception('number not Empty');

            // 数量合并
            $number = $shopping_number + $number;

            // 更新并删除
            $result = MemberShoppingCartModel::where(['id' => $find])->setInc('number', $number);

            MemberShoppingCartModel::destroy($cart_id);

        } else {

            $result = MemberShoppingCartModel::where(['id' => $cart_id, 'member_id' => $user_id])
                ->update(['price' => $price, 'attr' => $attr, 'number' => $number]);

        }

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];
    }

    /*
     * 用户端 - 购物车商品数量加减
     * @param  string $id       购物车ID
     * @param  string $number   数量
     */
    public function cart_reduce()
    {

        $id = Request::instance()->param('id');
        $number = Request::instance()->param('number');
        $type = Request::instance()->param('type');

        if (empty($id) || empty($number) || empty($type)) throw new Exception('not Empty');

        if ($type == '2') {

            // 查找购物车商品数量
            $find_number = MemberShoppingCartModel::where(['id' => $id])->value('number');

            if ($number <= $find_number) {

                if ($find_number == '1') {
                    $this->cart_destroy($id);
                }

                $result = MemberShoppingCartModel::where(['id' => $id])->setDec('number', $number);

                if ($result) {
                    return ['code' => 200, 'message' => '成功'];
                }

                return ['code' => 401, 'message' => '网络繁忙'];
            }

            return ['code' => 402, 'message' => '减少商品的数量大于库存数,请勿非法操作'];

        } else {

            // 查找商品数量
            $find_cart = Db::name('member_shopping_cart')
                ->where(['id' => $id])->field('goods_id,attr')->find();
            $find_number = Db::name('shopGoods')->where(['id'=>$find_cart['goods_id']])->value('inventory');
            if ($find_cart['attr']){   //有属性
                $find_number = Db::name('shopSpecAttr')
                    ->where(['goods_id' => $find_cart['goods_id'] , 'attribute' => $find_cart['attr']])
                    ->value('inventory');
            }

            if ($number < $find_number) {

                $result = MemberShoppingCartModel::where(['id' => $id])->setInc('number', $number);

                if ($result) {
                    return ['code' => 200, 'message' => '成功'];
                }

                return ['code' => 401, 'message' => '网络繁忙'];

            }

            return ['code' => 402, 'message' => '增加商品的数量大于库存数,请修改后重新提交'];

        }

    }

    /*
     * 用户端 - 删除购物车商品
     * @param  string $id  ID
     */
    public function cart_destroy($id)
    {

        if (empty($id)) throw new Exception('not Empty');

        $result = MemberShoppingCartModel::destroy($id);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }

    /*
     * 购物车专用数组分组
     *
     * @param object $data 二维数组
     * @param object $obj 对象
     */
    protected function cartGrouping($data, $val, $title, $list, $val2, $title2)
    {

        if (empty($data)) return [];

        $result = array_values(array_reduce($data, function ($value, $key) use ($val, $val2, $title, $title2, $list) {
            $name = $key[$val];
            $name2 = $key[$val2];
            unset($key[$val]);
            $value[$name][$title] = $name;
            $value[$name][$title2] = $name2;
            $value[$name][$list][] = $key;
            return $value;
        }));

        return $result;
    }

}
